package losrebellos.lospistoleros.components.media.image 
{
	import losrebellos.console.Console;
	import losrebellos.lospistoleros.core.model.sprite.PModelLoaderSprite;
	import losrebellos.lospistoleros.events.PLoadingEvent;
	import losrebellos.media.Library;

	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;

	/*
	 *
	 * @author los rebellos - ben@benoitvinay.com
	 *
	 */
	public class PIMGModel extends PModelLoaderSprite
	{
		/*
		 *
		 * VARIABLES
		 *
		 */
		protected var _request:URLRequest;
		protected var _context:LoaderContext;
		
		
		/*
		 *
		 * CONSTRUCTOR
		 *
		 */
		public function PIMGModel(name:String = null, type:String = null)
		{
			super(name, type);
		}

		
		/*
		 * 
		 * CONTENT
		 * 
		 */
		public function get url():String
		{
			return _request.url;
		}
		override public function load(request:URLRequest, context:LoaderContext = null):void
		{
			_request = request;
			_context = context;
			
			if(Library.instance.hasItem(_request.url))
			{
				this.dispatchEvent(new PLoadingEvent(PLoadingEvent.COMPLETE));
			}
			else
			{
				addEvents();
				super.load(_request, _context);
			}
		}

		
		/*
		 * 
		 * EVENTS
		 * 
		 */
		protected function addEvents():void
		{
			this.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS,progressHandler);
			this.contentLoaderInfo.addEventListener(Event.COMPLETE,completeHandler);
			this.contentLoaderInfo.addEventListener(ErrorEvent.ERROR,errorHandler);
			this.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			this.contentLoaderInfo.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
		}
		protected function removeEvents():void
		{
			this.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS,progressHandler);
			this.contentLoaderInfo.removeEventListener(Event.COMPLETE,completeHandler);
			this.contentLoaderInfo.removeEventListener(ErrorEvent.ERROR,errorHandler);
			this.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, errorHandler);
			this.contentLoaderInfo.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
		}
		
		
		/*
		 * 
		 * HANDLERS
		 * 
		 */
		protected function progressHandler(e:ProgressEvent):void
		{
			this.dispatchEvent(new PLoadingEvent(PLoadingEvent.PROGRESS, e.bytesLoaded / e.bytesTotal));
		}
		protected function completeHandler(e:Event):void
		{
			removeEvents();
			
			Library.instance.addItem(_request.url, this.content);
			
			this.dispatchEvent(new PLoadingEvent(PLoadingEvent.COMPLETE));
		}
		protected function errorHandler(e:Event):void
		{
			removeEvents();
			
			Console.output(this, "PIMGModel:errorHandler => " + _request.url + " / " + e);
			
			this.dispatchEvent(new PLoadingEvent(PLoadingEvent.ERROR));
		}
	}
}